package org.gruposp2p.dnie.server.rest;

import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gruposp2p.dnie.model.DNIeDocumentToSign;
import org.gruposp2p.dnie.model.DNIeDocumentToSignOption;
import org.gruposp2p.dnie.model.StatisticData;
import org.gruposp2p.dnie.model.StatisticOption;
import org.gruposp2p.dnie.service.DNIeDocumentToSignDAO;
import org.gruposp2p.dnie.service.DNIeDocumentToSignOptionDAO;
import org.gruposp2p.dnie.service.DNIeSignedDocumentDAO;
import org.gruposp2p.dnie.service.DNIeSignedDocumentOptionSelectedDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;

/**
 *
 * @author jj
 */
@Path(value = "/statistic/{documentToSignId}")
@Component
@Scope("request")
public class StatisticResource {

    private static Logger logger = LoggerFactory.getLogger(StatisticResource.class);

    @Autowired
    private DNIeSignedDocumentDAO signedDocumentDAO;
    @Autowired
    private DNIeDocumentToSignDAO documentToSignDAO;
    @Autowired
    private DNIeDocumentToSignOptionDAO documentToSignOptionDAO;
    @Autowired
    private DNIeSignedDocumentOptionSelectedDAO  signedDocumentOptionSelectedDAO;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(@PathParam("documentToSignId") Integer documentToSignId) {
        DNIeDocumentToSign  documentToSign =
        	documentToSignDAO.findById(documentToSignId);
        if (documentToSign == null)
        	Response.status(Status.NOT_FOUND).build();
        int numberResult = signedDocumentDAO.getNumberOfSignedItems(documentToSign);
        StatisticData statisticData = new StatisticData();
        statisticData.total = numberResult;
        List<DNIeDocumentToSignOption> documentToSignOptions =
                documentToSignOptionDAO.findByDocumentToSign(documentToSign);
        List<StatisticOption> statisticOptions = new ArrayList<StatisticOption>();
        for (DNIeDocumentToSignOption documentToSignOption : documentToSignOptions) {
            StatisticOption statisticOption = new StatisticOption();
            statisticOption.name = documentToSignOption.getContent();
            statisticOption.total =
                    signedDocumentOptionSelectedDAO.getNumberByDocumentToSignOption(documentToSignOption);
            statisticOptions.add(statisticOption);
        }
        statisticData.options = statisticOptions;
        return Response.ok().entity(statisticData).build();
    }

}
